//
//  WYLocationRangeController.m
//  Boss
//
//  Created by admin on 2018/6/5.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYLocationRangeController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "AMapTipAnnotation.h"
#import "WYRegionView.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "WYLocationViewCell.h"
//#import <AMapSearchKit/AMapSearchKit.h>
@interface WYLocationRangeController ()<UISearchBarDelegate, UISearchResultsUpdating,MAMapViewDelegate, AMapSearchDelegate,UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate>
{
    NSIndexPath *_indexPath;
    BOOL _isTouch;
}


@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) MAMapView *mapView;


@property (nonatomic, strong) NSMutableArray *tips;
@property (nonatomic, strong) NSMutableArray *busLines;

@property (nonatomic, strong) NSArray *circles;
@property (nonatomic,strong)WYRegionView *regionView;
@property (nonatomic,strong)UITableView *btmTableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong) AMapLocationManager *locationManager;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)UIButton *searchBtn;
@property (nonatomic,strong)CLLocation *location;
@property (nonatomic,strong)CLLocation *currentLocation;
@property (nonatomic,strong)UIButton *locationBtn;
@property (nonatomic,strong)AMapTip *tip;
@property (nonatomic,strong)AMapReGeocodeSearchResponse *response;
@property (nonatomic,strong) NSString *scopeName;
@property (nonatomic,assign) NSUInteger scopTag;
@end

@implementation WYLocationRangeController
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(NSMutableArray *)tips
{
    if (!_tips) {
        _tips = [[NSMutableArray alloc]init];
    }
    return _tips;
}
-(NSMutableArray *)busLines
{
    if (!_busLines) {
        _busLines = [[NSMutableArray alloc]init];
    }
    return _busLines;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self createTopView];
    //[self loadData];
    // Do any additional setup after loading the view.
}
-(void)sureLocation
{
    WEAKSELF
    self.locationManager = [[AMapLocationManager alloc]init];
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    
   
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        if (self.lastLoction.latitude>0&&self.lastLoction.longitude>0) {
            [self.mapView setCenterCoordinate:self.lastLoction];
        }else{
            [weakSelf.mapView setCenterCoordinate:location.coordinate];
            [weakSelf loadDataWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
        }
        
        
        weakSelf.location = location;
        weakSelf.currentLocation = location;
       
        [weakSelf addCircleWithLat:location.coordinate.latitude lon:location.coordinate.longitude];
        
        
        NSLog(@"location:%@", location);
        
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
        }
        
        
        
    }];
    
    
    
    
    
}
-(void)setupUI
{    
    [self initMapView];
    [self initTableView];
    [self createHeaderView];
    [self createBottomView];
    
    [self.mapView setZoomLevel:13.8];
    [self wr_setNavBarShadowImageHidden:YES];
}
-(void)addCircleWithLat:(CGFloat)lat lon:(CGFloat)lon
{
    NSMutableArray *arr = [NSMutableArray array];
    MACircle *circle1 = [MACircle circleWithCenterCoordinate:CLLocationCoordinate2DMake(lat, lon) radius:1500];
    [arr addObject:circle1];
    self.circles = [NSArray arrayWithArray:arr];
 //   self.mapView.centerCoordinate = CLLocationCoordinate2DMake(39.996441, 116.411146);
}



-(void)createHeaderView
{
    CGFloat height = 64;
    if (kDevice_Is_iPhoneX) {
        height = 88;
    }
    WYRegionView *topView = [[WYRegionView alloc]initWithFrame:CGRectMake(0, height, kScreenWidth, 62)];
    self.regionView = topView;
    topView.hidden = NO;
    
    
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    WEAKSELF
    topView.complete = ^(NSString *name, NSUInteger tag) {
        if (tag==0) {
            [weakSelf toast:@"钻石会员用户才有权发放\n全国范围红包信息哦~"];return ;
        }
        weakSelf.scopTag = tag;
        weakSelf.scopeName = name;
        
    };
}


-(void)returnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initMapView
{
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight-264)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    UIImageView *imageView = [[UIImageView alloc]init];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mapView);
        make.centerY.equalTo(self.mapView).offset(-14.5);
    }];
    
    imageView.image = [UIImage imageNamed:@"redLocation_icon"];
}

- (void)initSearchController
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.placeholder = @"请输入关键字";
    self.searchController.searchBar.showsCancelButton = NO;
    [self.searchController.searchBar sizeToFit];
    [self.searchController.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
    self.searchController.searchBar.tintColor = [UIColor whiteColor];
    
   // if (@available(iOS 11.0, *)) {
        CGFloat offsetY = 20;
        [self.searchController.searchBar setPositionAdjustment:UIOffsetMake(0, offsetY) forSearchBarIcon:(UISearchBarIconSearch)];
   // }
 
    //self.searchController.searchBar.height = 44;
    UIView *searchView = [[UIView alloc]init];
    searchView.backgroundColor = kColorMainColor;
    searchView.frame = CGRectMake(0, 0, kScreenWidth-56*2, 44);
    [searchView addSubview:self.searchController.searchBar];
    self.navigationItem.titleView = searchView;
    
    
    
    
    
    
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.searchController.active = NO;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.mapView.showsUserLocation = YES;
   // [self.mapView addOverlays:self.circles];
}


-(void)clickSureBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    if (searchController.active) {
        self.navigationItem.rightBarButtonItem = nil;
        self.regionView.hidden = YES;
        self.btmTableView.hidden = YES;
        NSLog(@"11111111111111");
    }else{
        self.regionView.hidden = YES;
        self.btmTableView.hidden = NO;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:(UIBarButtonItemStyleDone) target:self action:@selector(clickSureBtn)];
        NSLog(@"2222222222222222");
    }
    
    self.tableView.hidden = !searchController.isActive;
    [self searchTipsWithKey:searchController.searchBar.text];
   // searchController.searchBar.showsCancelButton = NO;
    if (searchController.isActive && searchController.searchBar.text.length > 0)
    {
        searchController.searchBar.placeholder = searchController.searchBar.text;
    }
}
#pragma mark - Utility
-(void)loadDataWithLatitude:(CGFloat)lat longitude:(CGFloat)lon
{
    AMapPOIAroundSearchRequest *tips = [[AMapPOIAroundSearchRequest alloc] init];
    tips.location =[AMapGeoPoint locationWithLatitude:lat longitude:lon];
    tips.sortrule            = 0;
    tips.requireExtension    = YES;
    [self.search AMapPOIAroundSearch:tips];
}
/* 输入提示 搜索.*/
- (void)searchTipsWithKey:(NSString *)key
{
    if (key.length == 0)
    {
        return;
    }
    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
    tips.keywords = key;
    //tips.city     = @"北京";
    
    //    tips.cityLimit = YES; 是否限制城市
    
    [self.search AMapInputTipsSearch:tips];
}
- (void)clear
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
}
- (void)clearAndShowAnnotationWithTip:(AMapTip *)tip
{
    /* 清除annotations & overlays */
    [self clear];
    
    if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
    {
        AMapTipAnnotation *annotation = [[AMapTipAnnotation alloc] initWithMapTip:tip];
        [self.mapView addAnnotation:annotation];
        [self.mapView setCenterCoordinate:annotation.coordinate];
        [self.mapView selectAnnotation:annotation animated:YES];
    }
    else if (tip.uid != nil && tip.location == nil)/* 公交路线，显示出来*/
    {
        AMapBusLineIDSearchRequest *request = [[AMapBusLineIDSearchRequest alloc] init];
   //     request.city                        = @"北京";
        request.uid                         = tip.uid;
        request.requireExtension            = YES;
        
        [self.search AMapBusLineIDSearch:request];
    }
    else if(tip.uid == nil && tip.location == nil)/* 品牌名，进行POI关键字搜索 */
    {
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
        request.keywords         = tip.name;
   //     request.city             = @"北京";
        request.requireExtension = YES;
        [self.search AMapPOIKeywordsSearch:request];
    }
}
/* 展示公交线路 */
- (void)presentCurrentBusLine
{

}

- (void)gotoDetailForTip:(AMapTip *)tip
{
}

- (void)gotoDetailForBusStop:(AMapBusStop *)busStop
{

}

- (void)gotoDetailForPoi:(AMapPOI *)poi
{

}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{

}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[AMapTipAnnotation class]])
    {
        static NSString *tipIdentifier = @"tipIdentifier";
        
        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:tipIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:tipIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        return poiAnnotationView;
    }
    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MACircle class]])
    {
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        
        circleRenderer.lineWidth   = 0.5f;
        circleRenderer.strokeColor = [UIColor hexStringToColor:@"#d8593f" alpha:0.08];
        circleRenderer.fillColor   = [[UIColor hexStringToColor:@"#d8593f" alpha:1.0] colorWithAlphaComponent:0.08];
        return circleRenderer;
    }
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 4.f;
        polylineRenderer.strokeColor = [UIColor magentaColor];
        
        return polylineRenderer;
    }
    return nil;
}
#pragma mark - AMapSearchDelegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
//    NSLog(@"Error: %@ - %@", error, [ErrorInfoUtility errorDescriptionWithCode:error.code]);
}

/* 输入提示回调. */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    if (response.count == 0)
    {
        return;
    }
    
    [self.tips setArray:response.tips];
    [self.tableView reloadData];
}

/* 公交搜索回调. */
- (void)onBusLineSearchDone:(AMapBusLineBaseSearchRequest *)request response:(AMapBusLineSearchResponse *)response
{
    if (response.buslines.count != 0)
    {
        [self.busLines setArray:response.buslines];
        
        [self presentCurrentBusLine];
    }
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    if (response.pois.count == 0)
    {
        return;
    }
    
    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
//        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
        
    }];
    
    /* 将结果以annotation的形式加载到地图上. */
    [self.mapView addAnnotations:poiAnnotations];
    
    /* 如果只有一个结果，设置其为中心点. */
    if (poiAnnotations.count == 1)
    {
        [self.mapView setCenterCoordinate:[poiAnnotations[0] coordinate]];
    }
    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
    else
    {
        [self.mapView showAnnotations:poiAnnotations animated:NO];
    }
    
    [self.dataArray setArray:response.pois];
    [self.btmTableView reloadData];
    [self tableView:self.btmTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.tips.count;
    }else{
        return self.dataArray.count;
    }
    
    
    
   // return self.tips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tipCellIdentifier = @"WYLocationViewCell";
    
    WYLocationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tipCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[NSBundle mainBundle]loadNibNamed:@"WYLocationViewCell" owner:nil options:nil].firstObject;
    }
    if (tableView==self.tableView) {
        AMapTip *tip = self.tips[indexPath.row];
        
        if (tip.location == nil)
        {
           // cell.imageView.image = [UIImage imageNamed:@"search"];
        }
//        cell.textLabel.textColor = [UIColor hexStringToColor:@"#222222" alpha:1.0];
//        cell.detailTextLabel.textColor = [UIColor hexStringToColor:@"#999999" alpha:1.0];
//        cell.textLabel.font = [UIFont systemFontOfSize:16];
//        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
        cell.titleLabel.text = tip.name;
        cell.deceLabel.text = tip.address;
        
//        cell.textLabel.text = tip.name;
//        cell.detailTextLabel.text = tip.address;
    }else{
        
        AMapTip *tip = self.dataArray[indexPath.row];
        
        if (tip.location == nil)
        {
           // cell.imageView.image = [UIImage imageNamed:@"search"];
        }
        cell.titleLabel.text = tip.name;
        cell.deceLabel.text = tip.address;
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_location_select"]];
        
        if (indexPath==_indexPath) {
            cell.accessoryView.hidden = NO;
        }else{
            cell.accessoryView.hidden = YES;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView) {
       // _isTouch = YES;
        [self.textField resignFirstResponder];
        AMapTip *tip = self.tips[indexPath.row];
       // [self clearAndShowAnnotationWithTip:tip];
        self.regionView.hidden = NO;
        self.btmTableView.hidden = NO;
        self.tableView.hidden = YES;
        self.searchBtn.selected = NO;
        
        AMapPOIAroundSearchRequest *tips = [[AMapPOIAroundSearchRequest alloc] init];
        tips.location =[AMapGeoPoint locationWithLatitude:tip.location.latitude longitude:tip.location.longitude];
        tips.sortrule            = 0;
        tips.requireExtension    = YES;
        [self.search AMapPOIAroundSearch:tips];
        
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(tip.location.latitude, tip.location.longitude) animated:YES];
//        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
//        regeo.location = [AMapGeoPoint locationWithLatitude:tip.location.latitude longitude:tip.location.longitude];
//        regeo.requireExtension =YES;
//        [self.search AMapReGoecodeSearch:regeo];
        
        
    }else{
        _isTouch = YES;
        [self.mapView removeAnnotations:self.mapView.annotations];
        AMapTip *tip = self.dataArray[indexPath.row];
        self.tip = tip;
        AMapTipAnnotation *annotation =[[AMapTipAnnotation alloc] initWithMapTip:tip];
       // [self.mapView addAnnotation:annotation];
       // [self.mapView setCenterCoordinate:annotation.coordinate];
       /// [self.mapView selectAnnotation:annotation animated:YES];
    
        UITableViewCell *celled = [tableView cellForRowAtIndexPath:_indexPath];
        celled.accessoryView.hidden=YES;
        _indexPath = indexPath;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryView.hidden=NO;
       
        if (self.locationBlock) {
            self.locationBlock(annotation.coordinate);
        }
        
        
        
//        if (self.address) {
//            self.address = <#^(NSString *province, NSString *city, NSString *district, NSString *formattedAddress)#>
//        }
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
     regeo.location = [AMapGeoPoint locationWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
         regeo.requireExtension =YES;
        [self.search AMapReGoecodeSearch:regeo];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

/* 逆地理编码回调. */

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response

{
    if (response.regeocode !=nil )
    {
        NSLog(@"反向地理编码回调:%@",response.regeocode.addressComponent.neighborhood);
        
        NSLog(@"反向地理编码回调:%@",response.regeocode.addressComponent.adcode);
        
        NSLog(@"反向地理编码回调:%@",response.regeocode.addressComponent.township);
        
        NSLog(@"反向地理编码回调:%@",response.regeocode.addressComponent.towncode);
        
        NSLog(@"反向地理编码回调:%@",response.regeocode.addressComponent.district);
        NSLog(@"%@",response.regeocode.formattedAddress);
        
        
        self.response = response;
        
        
        NSArray * addressArr = response.regeocode.pois;
        
        if (addressArr && addressArr.count >0) {
            
            AMapPOI *poiTemp = addressArr[0];
            
            NSLog(@"反向地理编码回调:%@",poiTemp.name);
        }
        
    }
    
    
    
}



#pragma mark - Initialization

- (void)initTableView
{
    //    CGFloat tableY = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight) style:UITableViewStylePlain];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYLocationViewCell" bundle:nil] forCellReuseIdentifier:@"WYLocationViewCell"];
    
    [self.view addSubview:self.tableView];
}
-(void)createTopView
{
    UIView *navView = [[UIView alloc]init];
    [self.view addSubview:navView];
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(self.navHeight);
    }];
    navView.backgroundColor = kColorMainColor;
    
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = kColorMainColor;
    [navView addSubview:topView];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    UITextField *textField = [[UITextField alloc]init];
    [topView addSubview:textField];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search"]];
    imageView.frame = CGRectMake(0, 0, 34, 30);
    
    textField.leftView =imageView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.top.mas_equalTo(5);
        make.bottom.mas_equalTo(-5);
        make.width.mas_equalTo(kScreenWidth-16-56-16);
    }];
    [textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
  //  textField.delegate = self;
    textField.placeholder = @"搜索地点";
    self.textField = textField;
    textField.backgroundColor = [UIColor whiteColor];
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    UIButton *sureBtn = [[UIButton alloc]init];
    [topView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(44);
    }];
    
  //  [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitle:@"取消" forState:UIControlStateNormal];
    self.searchBtn = sureBtn;
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [sureBtn addTarget:self action:@selector(clickSearchBtn:) forControlEvents:(UIControlEventTouchUpInside)];
}
-(void)clickSearchBtn:(UIButton *)sureBtn
{
    if (sureBtn.isSelected) {
        self.searchBtn.selected = NO;
        self.regionView.hidden = YES;
        self.btmTableView.hidden = NO;
        self.tableView.hidden = YES;
        [self.textField resignFirstResponder];
        sureBtn.selected = NO;
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


-(void)textFieldDidChange :(UITextField *)textField{
    if (textField.text.length) {
        self.regionView.hidden = YES;
        self.btmTableView.hidden = YES;
        self.locationBtn.hidden = YES;
        self.tableView.hidden = NO;
        self.searchBtn.selected = YES;
    }else{
        self.searchBtn.selected = NO;
        self.regionView.hidden = NO;
        self.btmTableView.hidden = NO;
        self.locationBtn.hidden = NO;
        self.tableView.hidden = YES;
    }
    [self searchTipsWithKey:textField.text];
}


-(void)createBottomView
{
    self.btmTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.btmTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.btmTableView.delegate = self;
    self.btmTableView.dataSource = self;
    [self.btmTableView registerNib:[UINib nibWithNibName:@"WYLocationViewCell" bundle:nil] forCellReuseIdentifier:@"WYLocationViewCell"];
    //self.btmTableView.hidden = YES;
    [self.view addSubview:self.btmTableView];
    
    [self.btmTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(264);
    }];
    
    
    UIButton *sureBtn = [[UIButton alloc]init];
    [self.view addSubview:sureBtn];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.btmTableView);
        make.bottom.mas_equalTo(-30);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(50);
    }];
    
    [sureBtn setTitle:@"确认" forState:(UIControlStateNormal)];
    [sureBtn setBackgroundColor:kColorMainColor];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [sureBtn setCornerRadius:25.f];
    [sureBtn addTarget:self action:@selector(changeLocationAndScope) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    UIButton *locationBtn = [[UIButton alloc]init];
    self.locationBtn = locationBtn;
    [self.view addSubview:locationBtn];
    [locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.bottom.mas_equalTo(-280);
    }];
    [locationBtn setImage:[UIImage imageNamed:@"currentLocation"] forState:UIControlStateNormal];
    
    [locationBtn addTarget:self action:@selector(clickLocationAction:) forControlEvents:(UIControlEventTouchUpInside)];
}
-(void)changeLocationAndScope
{
    if (self.complete&&self.scopTag) {
        self.complete(@"", self.scopeName, self.scopTag);
    }
    if (self.address) {
        self.address(self.response.regeocode.addressComponent.province, self.response.regeocode.addressComponent.city, self.response.regeocode.addressComponent.district,self.tip.address);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)clickLocationAction:(UIButton *)btn
{
    [self.mapView setCenterCoordinate:self.location.coordinate animated:YES];
    AMapPOIAroundSearchRequest *tips = [[AMapPOIAroundSearchRequest alloc] init];
    tips.location =[AMapGeoPoint locationWithLatitude:self.location.coordinate.latitude longitude:self.location.coordinate.longitude];
    tips.sortrule            = 0;
    tips.requireExtension    = YES;
    if (self.locationBlock) {
        self.locationBlock(self.location.coordinate);
    }
    
    
    [self.search AMapPOIAroundSearch:tips];
    
    
}



-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self sureLocation];
    self.navigationController.navigationBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
    
    if (_isTouch) {
        
        
        
    }else{
        AMapPOIAroundSearchRequest *tips = [[AMapPOIAroundSearchRequest alloc] init];
        tips.location =[AMapGeoPoint locationWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
        tips.sortrule            = 0;
        tips.requireExtension    = YES;
        if (self.locationBlock) {
            self.locationBlock(mapView.centerCoordinate);
        }
       //  [self.mapView setCenterCoordinate:mapView.centerCoordinate];
        
        [self.search AMapPOIAroundSearch:tips];
        
    }
    
    
    _isTouch = NO;
    
    
    //NSLog(@"123123123123123121232313123131231");
}
@end
